package CollectionBaseTest;

import java.util.*;

/**
 * Created by yexuan on 2018/3/2.
 */
public class CollectionsDemo {
    public static void main(String[] args) {
        reverseOrderDemo();
    }

    public static void reverseOrderDemo(){
        //强行逆转指定比较器的顺序
        TreeSet ts = new TreeSet(Collections.reverseOrder(new strLenComparator()));
        ts.add("abc");
        ts.add("aaa");
        ts.add("zz");
        ts.add("khhv");
        ts.add("z");

        System.out.println(ts);

    }

    public static void fillDemo(){
        List<String> list = new ArrayList<String>();
        list.add("abc");
        list.add("aaa");
        list.add("zz");
        list.add("khhv");
        list.add("z");

        System.out.println(list);

        //将集合中所有元素全部替换
//        Collections.fill(list,"cc");
        fillDemo(list,1,3);
        System.out.println(list);
    }

    //改部分元素
    public static void fillDemo(List list,int index , int end){
        List subList = list.subList(index,end);
        Collections.fill(subList,"cc");

    }

    public static void binarySearchDemo(){
        List<String> list = new ArrayList<String>();
        list.add("abc");
        list.add("aaa");
        list.add("zz");
        list.add("khhv");
        list.add("z");

        //按自然顺序排序
        Collections.sort(list,new strLenComparator());
        System.out.println(list);
        /*
        使用二分搜索法搜索指定列表,在调用之前，必须对列表元素进行排序
        如果搜索键包含在列表中，则返回搜索键的索引；否则返回 (-(插入点) - 1)。
        */
        int index = Collections.binarySearch(list,"aaa",new strLenComparator());

//        int index = halfSearch(list,"hh");

        System.out.println(index);
    }

    //二分法
    public static int halfSearch(List<String> list,String key){
        int max,min,mid;
        max = list.size()-1;
        min = 0;
        while(min<=max){
            mid = (max+min) >>1;
            String str = list.get(mid);
            int num = str.compareTo(key);
            if(num>0)
                max = mid-1;
            else if(num<0)
                min = mid+1;
            else
                return mid;
        }
        return -min-1;
    }

    public static void sortDemo(){
        List<String> list = new ArrayList<String>();
        list.add("abc");
        list.add("aaa");
        list.add("zz");
        list.add("khhv");
        list.add("z");

        //按自然顺序排序
//        Collections.sort(list);

        //按自定义顺序排序（str长度为主）
        Collections.sort(list,new strLenComparator());

        System.out.println(list);
    }
}

class strLenComparator implements Comparator<String>{
    public int compare(String s1,String s2)
    {
        int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
        if(num==0){
            return s1.compareTo(s2);
        }

        return num;
    }
}
